package com.zhike.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Slf4j
public class AliSecurityCheckUtils {

    private static final String ACCESS_KEY_ID = "LTAI5tSnjz1K7UcP3V4KtopZ";
    private static final String ACCESS_KEY_SECRET = "3TYdfpFPkZpKMID4YwSd3e2aA1KgCZ";
    private static final String REGION_ID_SHANGHAI = "cn-shanghai";
    private static final String ENDPOINT_SHANGHAI = "green-cip.cn-shanghai.aliyuncs.com";
    private static final String REGION_ID_BEIJING = "cn-beijing";
    private static final String ENDPOINT_BEIJING = "green-cip.cn-beijing.aliyuncs.com";


    public static Boolean textScan(String text, String serverCode) {
        if (text == null || text.trim().isEmpty()) {
            log.warn("文本内容不能为空");
            return null;
        }

        try {
            Client client = createClient(REGION_ID_SHANGHAI, ENDPOINT_SHANGHAI);
            TextModerationRequest request = createRequest(text, serverCode);
            RuntimeOptions runtime = createRuntimeOptions();

            TextModerationResponse response = client.textModerationWithOptions(request, runtime);

            if (response != null && response.getStatusCode() == 500) {
                log.warn("请求失败 启用北京节点重试");
                client = createClient(REGION_ID_BEIJING, ENDPOINT_BEIJING);
                response = client.textModerationWithOptions(request, runtime);
            }

            return handleResponse(response);
        } catch (Exception e) {
            log.error("Error during text moderation: {}", e);
            return null;
        }
    }

    public static Boolean imageScan(String url, String serverCode) {
        if (url == null || url.trim().isEmpty()) {
            log.warn("图片地址不能为空");
            return false;
        }

        try {
            Client client = createClient(REGION_ID_SHANGHAI, ENDPOINT_SHANGHAI);
            //创建文件请求对象
            // 检测参数构造。
            Map<String, String> serviceParameters = new HashMap<>();
            //公网可访问的URL。
            serviceParameters.put("imageUrl", url);
            //待检测数据唯一标识
            serviceParameters.put("dataId", UUID.randomUUID().toString());

            ImageModerationRequest request = new ImageModerationRequest();
            // 图片检测service：内容安全控制台图片增强版规则配置的serviceCode，示例：baselineCheck
            // 支持service请参考：https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
            request.setService(serverCode);
            request.setServiceParameters(JSON.toJSONString(serviceParameters));
            RuntimeOptions runtime = createRuntimeOptions();

            ImageModerationResponse response = client.imageModerationWithOptions(request, runtime);

            if (response != null && response.getStatusCode() == 500) {
                log.warn("请求失败 启用北京节点重试");
                client = createClient(REGION_ID_BEIJING, ENDPOINT_BEIJING);
                response = client.imageModerationWithOptions(request, runtime);
            }

            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageModerationResponseBody body = response.getBody();
                    log.warn("imagescan start");
                    log.warn("requestId=" + body.getRequestId());
                    log.warn("code=" + body.getCode());
                    log.warn("msg=" + body.getMsg());
                    if (body.getCode() == 200) {
                        ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
                        log.warn("riskLevel:" + data.getRiskLevel());
                        if (!data.getRiskLevel().equals("none")){
                          return false;
                      }else {
                          return true;
                      }
                    } else {
                        log.warn("image moderation not success. code:" + body.getCode());
                    }
                } else {
                    log.warn("response not success. status:" + response.getStatusCode());
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static Client createClient(String regionId, String endpoint) throws Exception {
        Config config = new Config();
        config.setAccessKeyId(ACCESS_KEY_ID);
        config.setAccessKeySecret(ACCESS_KEY_SECRET);
        config.setRegionId(regionId);
        config.setEndpoint(endpoint);
        config.setReadTimeout(6000);
        config.setConnectTimeout(3000);
        return new Client(config);
    }

    private static TextModerationRequest createRequest(String text, String serverCode) {
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", text);

        TextModerationRequest request = new TextModerationRequest();
        request.setService(serverCode);
        request.setServiceParameters(serviceParameters.toJSONString());
        return request;
    }

    private static RuntimeOptions createRuntimeOptions() {
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;
        return runtime;
    }

    private static Boolean handleResponse(TextModerationResponse response) {
        if (response == null) {
            log.warn("Response is null");
            return null;
        }

        if (response.getStatusCode() == 200) {
            TextModerationResponseBody result = response.getBody();
            log.debug("Response: {}", JSON.toJSONString(result));
            Integer code = result.getCode();
            if (code != null && code == 200) {
                if (StringUtils.isBlank(result.getData().getReason())) {
                    return Boolean.TRUE;
                } else {
                    log.info("{}", result);
                }
            } else {
                log.warn("Text moderation not successful. Code: {}", code);
            }
        } else {
            log.warn("Response not successful. Status: {}", response.getStatusCode());
        }

        return Boolean.FALSE;
    }
}
